<?php
require 'includes/config.php';
require 'includes/auth.php';
require 'includes/sanitize.php';

$data = sanitize($_GET);
$accesstoken = $_SESSION['accesstoken'];
$uid = $_SESSION['uid'];
// check for relation between current users id and any other user id
$request = new makeRequest($backend.'api.php?method=friends&id='.$uid, 'GET');
$tmp = $request->makeRequest();
$rbody = $tmp[0];
$http_code = $tmp[1];
$obj = json_decode($rbody);
if($http_code==200){
	// Check if some friend should be deleted
	if(isset($_GET['delete'])){
		$request = new makeRequest($backend.'api.php?method=friends&accesstoken='.$accesstoken.'&id='
		.$data['delete'].'&auid='.$uid, 'DELETE');
		$tmp = $request->makeRequest();
		$rbody = $tmp[0];
		$http_code = $tmp[1];
		if($http_code==200){
			$msg.="<p>Friend deleted";
		}
	}
	// Handle (accept) friend requests
	if(isset($data['friend'])){
		$request = new makeRequest($backend.'api.php','POST','method=friends&id='.$data['friend'].
		'&accesstoken='.$accesstoken."&auid=$uid");
		$tmp = $request->makeRequest();
		$http_code = $tmp[1];
		if($http_code == 200){
			$msg = "Friend accept successfull";
		}
	}
	// Add all friends ids to array
	$request = new makeRequest($backend.'api.php?method=friends&id='.$uid.'&accesstoken='.$accesstoken, 'GET');
	$tmp = $request->makeRequest();
	$rbody = $tmp[0];
	$http_code = $tmp[1];
	$obj = json_decode($rbody);
	if($http_code == 200){
		// Check so the request was successful
		foreach($obj as &$fid){
			$userids[] =  $fid;
			$friendsFound = true;
		}
	}
	// Generate friendlist from array
	if($friendsFound){
		// Beginning of friendlist table
		$msg.="<table border='1'>
				<th>Username</th>
				<th>Mail</th>
				<th>First name</th>
				<th>Last name</th>
				<th>Age</th>
				<th>Location</th>
				<th>Delete</th>";
		foreach($userids as &$userid){
			$request = new makeRequest($backend.'api.php?method=user&id='.$userid, 'GET');
			$tmp = $request->makeRequest();
			$rbody = $tmp[0];
			$http_code = $tmp[1];
			if($http_code == 200){
				$obj = json_decode($rbody);
				// Adding a row with userinfo
				$msg.="<tr>
						<td><a href=profile.php?status=true&username=".$obj[0]->{'username'}.">".$obj[0]->{'username'}."</a></td>
						<td>".$obj[0]->{'mail'}."</td>
						<td>".$obj[0]->{'firstname'}."</td>
						<td>".$obj[0]->{'lastname'}."</td>
						<td>".$obj[0]->{'age'}."</td>
						<td>".$obj[0]->{'location'}."</td>
						<td><a href=friends.php?delete=".$userid.">Delete friend</a></td></tr>";		
			}
		}
		$msg.="</table>";
	}else{ // If the user doesn't have any friend relations to display
		$msg.="<p>No friends found</p>";
	}
}
require 'includes/header.php';
require 'includes/topmenu.php';
echo '<div id="kaka">';
require 'includes/sidemenu.php'
?>
<div id="content">

<?php
/* Content shown on page */
echo $msg;

require 'includes/footer.php';
?>